<!-- 发布信息 -->
<template>
	<view class="page-content">
		<view class="scroll-Y pagebt75">
			<u-navbar title="发布信息" :is-back="false" :background="background"></u-navbar>

			<u-form :model="formData" ref="uForm">
				<view class="m-3 py-4 px-3 form rounded-8">
					<view class="font-md font-weight text-main">项目基本信息</view>
					<u-form-item
						class="required projectNameScroll"
						label="项目名称"
						label-position="top"
						:border-bottom="false"
					>
						<u-input border height="80" v-model="formData.projectName" placeholder="请输入项目名称" />
					</u-form-item>
					<u-form-item
						class="required infoTypeScroll"
						label="信息类型"
						label-position="top"
						:border-bottom="false"
					>
						<hpy-form-select
							:dataList="infoTypeList"
							text="label"
							name="value"
							v-model="formData.infoType"
							title="请选择信息类型"
							hideBorder
						/>
					</u-form-item>

					<u-form-item
						class="required projectStageScroll"
						label="项目阶段"
						label-position="top"
						:border-bottom="false"
					>
						<hpy-form-select
							:dataList="projectPhase2List"
							text="label"
							name="value"
							v-model="formData.projectStage"
							title="请选择项目阶段"
							hideBorder
						/>
					</u-form-item>
					<u-form-item
						class="required projectAddressNameScroll"
						label="项目地址"
						label-position="top"
						:border-bottom="false"
					>
						<view class="position-relative w-100 ">
							<u-input
								border
								height="80"
								v-model="formData.projectAddressName"
								placeholder="请输入项目地址"
              />
              <text
                style="z-index: 9; height: 100rpx; width: 100rpx; text-align: right;"
                class="position-absolute right-2 top-4 iconfont icon-calendar-todo-fill text-primary"
                @click="getAddressFn"
              ></text>
            </view>
          </u-form-item>
          <u-form-item
            class="required outputScaleScroll"
            label="预计产值规模"
            label-position="top"
            :border-bottom="false"
          >
            <u-input border height="80" type="number" v-model="formData.outputScale" placeholder="请输入预计产值规模" />
          </u-form-item>
          <u-form-item label="项目备注" label-position="top" :border-bottom="false">
            <u-input
              border
              height="120"
              type="textarea"
              v-model="formData.projectRemark"
              placeholder="请输入项目备注"
						/>
					</u-form-item>
				</view>

				<view class="m-3 py-4 px-3 form rounded-8" v-if="formData.projectStage == 'BidTender'">
					<view class="font-md font-weight text-main">招标信息</view>
					<u-form-item
						class="required qualificationsScroll"
						label="资质要求"
						label-position="top"
						:border-bottom="false"
					>
						<u-input border height="80" v-model="formData.qualifications" placeholder="请输入资质要求" />
					</u-form-item>

					<u-form-item
						class="required tenderClosingDateScroll"
						label="招标获取截止时间"
						label-position="top"
						:border-bottom="false"
					>
						<view class="position-relative w-100 " @click="openexpireDatePicker">
							<u-input
								border
								height="80"
								v-model="formData.tenderClosingDate"
								placeholder="请输入招标获取截止时间"
								@click="openexpireDatePicker"
							/>
							<text
								style="z-index: 9; height: 100rpx; width: 100rpx; text-align: right;"
								class="position-absolute right-2 top-4 iconfont icon-xiajiantou u-font-28 text-tips"
							></text>
						</view>
					</u-form-item>

					<u-form-item
						class="required deadlineForBiddingScroll"
						label="招标截止时间"
						label-position="top"
						:border-bottom="false"
					>
						<view class="position-relative w-100 " @click="openexpireDatePicker2">
							<u-input
								border
								height="80"
								v-model="formData.deadlineForBidding"
								placeholder="请输入招标截止时间"
								@click="openexpireDatePicker2"
							/>
							<text
								style="z-index: 9; height: 100rpx; width: 100rpx; text-align: right;"
								class="position-absolute right-2 top-4 iconfont icon-xiajiantou u-font-28 text-tips"
							></text>
						</view>
					</u-form-item>

					<u-form-item label="资金来源" label-position="top" :border-bottom="false">
						<u-input border height="80" v-model="formData.fundingSource" placeholder="请输入资金来源" />
					</u-form-item>
					<u-form-item label="工程规模" label-position="top" :border-bottom="false">
						<u-input border height="80" v-model="formData.projectScale" placeholder="请输入工程规模" />
					</u-form-item>
					<u-form-item label="工期要求" label-position="top" :border-bottom="false">
						<u-input border height="80" v-model="formData.durationRequired" placeholder="请输入工期要求" />
					</u-form-item>
					<u-form-item label="招标范围" label-position="top" :border-bottom="false">
						<u-input border height="80" v-model="formData.tenderScope" placeholder="请输入招标范围" />
					</u-form-item>
					<u-form-item label="招标控制价" label-position="top" :border-bottom="false">
						<u-input
							border
							height="80"
							type="number"
							v-model="formData.tenderControlPrice"
							placeholder="请输入招标控制价"
						/>
					</u-form-item>
					<u-form-item label="保证金金额" label-position="top" :border-bottom="false">
						<u-input
							border
							height="80"
							type="number"
							v-model="formData.bond"
							placeholder="请输入保证金金额"
						/>
					</u-form-item>

					<u-form-item label="缴纳保证金截止时间" label-position="top" :border-bottom="false">
						<view class="position-relative w-100 " @click="openexpireDatePicker3">
							<u-input
								border
								height="80"
								v-model="formData.bondEndTime"
								placeholder="请输入缴纳保证金截止时间"
								@click="openexpireDatePicker3"
							/>
							<text
								style="z-index: 9; height: 100rpx; width: 100rpx; text-align: right;"
								class="position-absolute right-2 top-4 iconfont icon-xiajiantou u-font-28 text-tips"
							></text>
						</view>
					</u-form-item>
				</view>

				<view class="m-3 py-4 px-3 form rounded-8">
					<view class="font-md font-weight text-main">项目方</view>
					<u-form-item
						class="required ownerCompanyNameScroll"
						label="业主方公司名称"
						label-position="top"
						:border-bottom="false"
					>
						<u-input
							border
							height="80"
							v-model="formData.ownerCompanyName"
							placeholder="请输入业主方公司名称"
						/>
					</u-form-item>
					<u-form-item label="施工方公司名称" label-position="top" :border-bottom="false">
						<u-input
							border
							height="80"
							v-model="formData.constructionName"
							placeholder="请输入施工方公司名称"
						/>
					</u-form-item>
				</view>

				<view class="m-3 py-4 px-3 form rounded-8">
					<view class="u-flex u-row-between">
						<view class="font-md font-weight text-main">指派目标企业</view>
						<view @click="addTargetFn" class="iconfont custom-icon-node-collapse text-primary font-lg"></view>
					</view>
					<view class="pb-2 cropanyBox" v-for="(item, index) in formData.busiIndustryAssignList" :key="index">
						<u-form-item
							class="required position-relative busiIndustryAssignListScroll"
							label="产业标记"
							label-position="top"
							:border-bottom="false"
						>
							<hpy-form-select
								:dataList="getAvailableIndustrialMarks(index)"
								text="name"
								name="dictId"
								v-model="item.industryId"
								title="请选择产业标记"
								@change="changeMarkFn(index)"
								hideBorder
							/>
							<view
								v-if="index != 0"
								class="position-absolute top-6 right-0 iconfont custom-icon-node-expand font-md text-error font-weight"
								@click="delMarksFn(index)"
							></view>
						</u-form-item>
						<!-- @change="e => queryBureauFn((e, index))" -->
						<u-form-item label="指派目标企业" label-position="top" :border-bottom="false">
							<view class="bg-grey rounded-8 w-100 px-2 py">
								<view class="bb inputHight font-sm text-tips" @click="addCorpFn(index)">
									<text class="iconfont custom-icon-node-collapse text-primary pr-2"></text>
									添加新企业
								</view>
								<view class="bb inputHight " v-for="(i, x) in item.busiIndustryCompanyList" :key="x">
									<view class="d-flex j-sb a-center">
										<view class="font-sm text-tips">{{ i.companyName }}</view>
										<view
											class="iconfont icon-shanchu text-error"
											@click="delcropFn(index, i)"
										></view>
									</view>
								</view>
							</view>
						</u-form-item>
					</view>
				</view>
			</u-form>
		</view>
		<view class="subarea">
			<button class="warningBnt btn-cancel font-weight-100" @click="hanglgCancelFn">取 消</button>
			<button class="primaryBnt btn-submit font-weight-100" @click="hanglgSubmitFn">提 交</button>
		</view>
    
		<atl-map
			v-if="showMap"
			:longitude="formData.longitude"
			:latitude="formData.latitude"
      :projectAddressName="formData.projectAddressName"
			:mapKey="usingKey"
			:mapType="mapType"
			@confirm="confirmMap"
			@changeMarker="changeMarker"
		>
			<template v-slot:content>
			</template>
		</atl-map>
		<datetime-picker
			ref="myPicker"
			@submit="handlexpireDatePicker"
			:start-year="2000"
			:end-year="2099"
			:time-init="Date.now()"
			:time-hide="[true, true, true, false, false, false]"
			:time-label="['年', '月', '日', '时', '分', '秒']"
		/>
		<datetime-picker
			ref="myPicker2"
			@submit="handlexpireDatePicker2"
			:start-year="2000"
			:end-year="2099"
			:time-init="Date.now()"
			:time-hide="[true, true, true, false, false, false]"
			:time-label="['年', '月', '日', '时', '分', '秒']"
		/>
		<datetime-picker
			ref="myPicker3"
			@submit="handlexpireDatePicker3"
			:start-year="2000"
			:end-year="2099"
			:time-init="Date.now()"
			:time-hide="[true, true, true, false, false, false]"
			:time-label="['年', '月', '日', '时', '分', '秒']"
		/>
	</view>
</template>
<script>
import { infoTypeList, projectPhaseList, projectPhase2List } from '@/utils/data.js';
import atlMap from '@/components/atl-map/atl-map.vue';
import {
	getDictByParentId,
	addBusiInfoData,
	updateBusiInfoData,
	getbusiInfoData,
	getPlaceByAddress,
	getPlaceByLocation
} from '@/api/apis.js';
export default {
  components: {
    atlMap
  },
  onReady() {
    uni.hideTabBar();
  },
  data() {
    return {
      background: {
        backgroundColor: '#fff'
      },

      formData: {
        projectName: '',
        infoType: '',
        projectStage: '',
        province: '',
        provinceCode: '',
        city: '',
        cityCode: '',
        projectAddressName: '',
        longitude: '',
        latitude: '',
        outputScale: '',
        projectRemark: '',
        ownerCompanyName: '',
        constructionName: '',
        busiIndustryAssignList: [
          {
            industryId: '',
            industryName: '',
            busiIndustryCompanyList: []
          }
        ],
        qualifications: '',
        tenderClosingDate: '',
        deadlineForBidding: '',
        fundingSource: '',
        projectScale: '',
        durationRequired: '',
        tenderScope: '',
        tenderControlPrice: null,
        bond: null,
        bondEndTime: ''
      },
      usingKey: 'NALBZ-ALBCM-ZFO6I-6L5UY-PDNNQ-RDBVI', //实际使用的KEY
      showMap: false,
      mapType: 'bmap', // tmap bmap amap
      initLocation: '',
      infoTypeList, //信息类型
      projectPhaseList, //项目阶段
      projectPhase2List, //项目阶段
      industrialMarkList: [],
      certificateTypeList: [],
      selectedIndustryIds: [] // 用于跟踪已经选择的产业标记ID
    };
  },
  onLoad() {
    this.getDictFn();
    uni.$on('globleEvent', rel => {
      this.formData.busiIndustryAssignList[rel.index].busiIndustryCompanyList = [];
      rel.data.forEach(x => {
        if (this.formData.busiIndustryAssignList[rel.index].busiIndustryCompanyList) {
          this.formData.busiIndustryAssignList[rel.index].busiIndustryCompanyList.push(x);
        }
      });
    });
    if (this.$Route.query.busiInfoId) {
      this.getbusiInfoDataFn(this.$Route.query.busiInfoId);
    }
  },
  methods: {    
    /**
     * @description 获取可用的产业标记
     * @param {Object} currentIndex
     */
    getAvailableIndustrialMarks(currentIndex) {
      // 返回当前选择器可用的产业标记列表（排除已选中的）
      return this.industrialMarkList.filter(mark => {
        // 检查产业标记是否已被之前的选择器选中
        return !this.selectedIndustryIds.slice(0, currentIndex).includes(mark.value);
      });
    },
    
    /**
     * @description 更换产业标记
     * @param {Object} index
     */
    changeMarkFn(index) {
      this.formData.busiIndustryAssignList[index].busiIndustryCompanyList = [];
      const selectedId = this.formData.busiIndustryAssignList[index].industryId;
      // 检查当前选择的产业标记是否与之前选择的不同
      const previousSelection = this.selectedIndustryIds[index];
      if (selectedId && previousSelection !== selectedId && this.selectedIndustryIds.includes(selectedId)) {
        // 如果当前选择的是一个新的且已被之前选择器选中的产业标记，则显示提示并重置选择
        uni.showToast({ title: '该产业标记已被选择，请选择其他标记', icon: 'none' });
        this.formData.busiIndustryAssignList[index].industryId = '';
      } else {
        // 如果当前选择的是一个新的或未被选中的产业标记，则更新记录
        this.selectedIndustryIds[index] = selectedId;
      }
    },
    
    /**
     * @description 删除指派目标企业
     * @param {Object} index
     */
    delMarksFn(index) {
      this.formData.busiIndustryAssignList.splice(index, 1);
      this.selectedIndustryIds.splice(index, 1);
    },
    
    /**
     * @description 切换KEY
     */
    getAddressFn() {
      // #ifdef MP-WEIXIN
      this.usingKey = 'NALBZ-ALBCM-ZFO6I-6L5UY-PDNNQ-RDBVI';
      // #endif
      // #ifndef MP-WEIXIN
      this.usingKey = '';
      // #endif
      this.$nextTick(() => {
        this.showMap = true;
      })
    },
    
    /**
     * @description 确认地图点选事件
     * @param {Object} e
     */
    async confirmMap(e) {
      if (e) {
        this.formData.longitude = e.longitude;
        this.formData.latitude = e.latitude;
        this.formData.projectAddressName = e.address;
        await this.getNowPlace(this.formData.longitude, this.formData.latitude);
      }
      this.showMap = false;
    },
    
    /**
     * @description 根据经纬度查询地址
     * @param {Object} lng
     * @param {Object} lat
     */
    getNowPlace(lng, lat) {
      return new Promise(resolve => {
        getPlaceByLocation({lat: lat, lng: lng}).then(res => {
          if (res.code == 10000) {
            let result = res.data.result;
            this.formData.province = result.addressComponent.province;
            this.formData.city = (result.addressComponent.city === '北京市' || result.addressComponent.city === '天津市' || result.addressComponent.city === '上海市' || result.addressComponent.city === '重庆市') ? result.addressComponent.district : result.addressComponent.city;
          } else {
            this.$u.toast(res.msg);
          }
        }).catch(err => {}).finally(() => {
          resolve();
        });
      })
    },
    
    /**
     * @description 获取产业标记数据
     */
    getDictFn() {
      getDictByParentId({ parentId: 'COMPANY_SERVICE' }).then(res => {
        if (res.code == 10000) {
          this.industrialMarkList = res.data;
          this.industrialMarkList.forEach(x => {
            this.$set(x, 'label', x.name);
            this.$set(x, 'value', x.dictId);
          });
        } else {
          this.$u.toast(res.msg);
        }
      });
    },
    
    /**
     * @description 添加新公司
     * @param {Object} index
     */
    addCorpFn(index) {
      if (!this.formData.busiIndustryAssignList[index].industryId) {
        this.$u.toast('请选择产业标记');
        return false;
      }
      this.$Router.push({
        path: '/detailPages/pages/joinCompany/index',
        query: {
          index: index,
          industryId: this.formData.busiIndustryAssignList[index].industryId,
          busiIndustryCompanyList: this.formData.busiIndustryAssignList[index].busiIndustryCompanyList.map(
            item => item.companyId
          )
        }
      });
    },
    
    /**
     * @description 增加备选公司
     */
    addTargetFn() {
      this.formData.busiIndustryAssignList.push({
        industryId: '',
        industryName: '',
        busiIndustryCompanyList: []
      });
    },

    /**
     * @description 删除已选公司
     * @param {Object} index
     * @param {Object} i
     */
    delcropFn(index, i) {
      this.formData.busiIndustryAssignList[index].busiIndustryCompanyList.splice(i, 1);
    },
    
    /**
     * @description 提交
     */
    hanglgSubmitFn() {
      if (this.validRuleFn()) {
        if (this.$Route.query.busiInfoId) {
          updateBusiInfoData({...this.formData}).then(res => {
            if (res.code == 10000) {
              this.$Router.replaceAll({
                path: '/pages/infoManagement/index',
                query: {
                  current: 1
                }
              });
            } else {
              this.$u.toast(res.msg);
            }
          });
        } else {
          addBusiInfoData({...this.formData}).then(res => {
            if (res.code == 10000) {
              this.$Router.replaceAll({
                path: '/pages/infoManagement/index',
                query: {
                  current: 1
                }
              });
            } else {
              this.$u.toast(res.msg);
            }
          });
        }
      }
    },
    
    /**
     * @description 获取项目详情
     * @param {Object} id
     */
    getbusiInfoDataFn(id) {
      getbusiInfoData({ busiInfoId: id }).then(res => {
        if (res.code == 10000) {
          this.formData = res.data;
        } else {
          this.$u.toast(res.msg);
        }
      });
    },

    /**
     * @description 标记点选事件
     * @param {Object} e
     */
    changeMarker(e) {
      const { latitude, longitude } = e;
    },
    
    /**
     * @description 表单校验
     */
    validRuleFn() {
      if (this.formData.projectName == '') {
        this.$u.toast('请输入项目名称');
        uni.pageScrollTo({
          selector: '.projectNameScroll',
          duration: 300
        });
        return false;
      }
      if (this.formData.infoType == '') {
        this.$u.toast('请选择信息类型');
        uni.pageScrollTo({
          selector: '.infoTypeScroll',
          duration: 300
        });
        return false;
      }
      if (this.formData.projectStage == '') {
        this.$u.toast('请选择项目阶段');
        uni.pageScrollTo({
          selector: '.projectStageScroll',
          duration: 300
        });
        return false;
      }
      if (this.formData.projectAddressName == '') {
        this.$u.toast('请选择项目地址');
        uni.pageScrollTo({
          selector: '.projectAddressNameScroll',
          duration: 300
        });
        return false;
      }
      if (this.formData.outputScale == '') {
        this.$u.toast('请输入预计产值规模');
        uni.pageScrollTo({
          selector: '.outputScaleScroll',
          duration: 300
        });
        return false;
      }
    
      if (this.formData.projectStage == 'BidTender') {
        if (this.formData.qualifications == '') {
          this.$u.toast('请输入资质要求');
          uni.pageScrollTo({
            selector: '.qualificationsScroll',
            duration: 300
          });
          return false;
        }
        if (this.formData.tenderClosingDate == '') {
          this.$u.toast('请输入招标获取截止时间');
          uni.pageScrollTo({
            selector: '.tenderClosingDateScroll',
            duration: 300
          });
          return false;
        }
        if (this.formData.deadlineForBidding == '') {
          this.$u.toast('请输入招标截止时间');
          uni.pageScrollTo({
            selector: '.deadlineForBiddingScroll',
            duration: 300
          });
          return false;
        }
      }
    
      if (this.formData.ownerCompanyName == '') {
        this.$u.toast('请输入业主方公司名称');
        uni.pageScrollTo({
          selector: '.ownerCompanyNameScroll',
          duration: 300
        });
        return false;
      }
    
      for (let i of this.formData.busiIndustryAssignList) {
        if (i.industryId == '') {
          this.$u.toast('请选择产业标记');
          uni.pageScrollTo({
            selector: '.busiIndustryAssignListScroll',
            duration: 300
          });
          return;
        }
      }
    
      return true;
    },
    
    /**
     * @description 取消提交
     */
    hanglgCancelFn() {
      this.$Router.replaceAll({
        path: '/pages/home/index'
      });
    },
    
    /**
     * @description 日期选择方案
     */
    openexpireDatePicker() {
      this.$refs.myPicker.show();
    },
    handlexpireDatePicker(e) {
      this.formData.tenderClosingDate = `${e.year}-${e.month}-${e.day}`;
    },
    openexpireDatePicker2() {
      this.$refs.myPicker2.show();
    },
    handlexpireDatePicker2(e) {
      this.formData.deadlineForBidding = `${e.year}-${e.month}-${e.day}`;
    },
    openexpireDatePicker3() {
      this.$refs.myPicker3.show();
    },
    handlexpireDatePicker3(e) {
      this.formData.bondEndTime = `${e.year}-${e.month}-${e.day}`;
    }
  }
};
</script>

<style lang="scss" scoped>
.form {
	background-color: #fff;
	::v-deep .select-picker {
		width: 628rpx !important;
	}
	.inputHight {
		height: 40px;
	}
	.cropanyBox {
		border-bottom: 1px solid #f3f5f8;
		.bb :last-child {
			border-bottom: none !important;
		}
	}
}
</style>
